using EIMS.Models.Identity;
using Microsoft.AspNetCore.Identity;

namespace EIMS.Data
{
    public static class DbInitializer
    {
        public static async Task InitializeAsync(IServiceProvider serviceProvider)
        {
            var roleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();
            var userManager = serviceProvider.GetRequiredService<UserManager<ApplicationUser>>();

            // 创建默认角色
            string[] roleNames = { "Administrator", "Manager", "User" };
            foreach (var roleName in roleNames)
            {
                if (!await roleManager.RoleExistsAsync(roleName))
                {
                    await roleManager.CreateAsync(new IdentityRole(roleName));
                }
            }

            // 创建默认管理员账户
            string adminUserName = "admin";
            var adminUser = await userManager.FindByNameAsync(adminUserName);
            if (adminUser == null)
            {
                var admin = new ApplicationUser
                {
                    UserName = adminUserName,
                    Email = "admin@example.com",
                    DisplayName = "系统管理员",
                    EmailConfirmed = true,
                    CreatedDate = DateTime.Now,
                    IsActive = true
                };

                var result = await userManager.CreateAsync(admin, "Admin@123");
                if (result.Succeeded)
                {
                    await userManager.AddToRoleAsync(admin, "Administrator");
                }
            }
        }
    }
} 